<?php

/**
 * contact : 刘经理 19326416371
 * company : 版权所属 四川北星惯牌科技有限公司
 **/

namespace app\adminapi\controller\auth;

use app\admin\model\AuthGroup;
use app\admin\model\AuthGroupAccess;
use app\common\controller\BackendApi;
use fast\Random;
use fast\Tree;
use think\Db;
use think\Validate;

/**
 * 管理员管理
 *
 * @icon   fa fa-users
 * @remark 一个管理员可以有多个角色组,左侧的菜单根据管理员所拥有的权限进行生成
 */
class Admin extends BackendApi
{

    protected $noNeedRight = ['groups'];
    /**
     * @var \app\admin\model\Admin
     */
    protected $model = null;
    protected $selectpageFields = 'id,username,nickname,avatar';
    protected $searchFields = 'id,username,nickname';
    protected $childrenGroupIds = [];
    protected $childrenAdminIds = [];

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Admin();

        $this->childrenAdminIds = $this->auth->getChildrenAdminIds($this->auth->isSuperAdmin());
        $this->childrenGroupIds = $this->auth->getChildrenGroupIds($this->auth->isSuperAdmin());
    }

    public function groups()
    {
        $data = $this->auth->getGroupList();
        $this->success('获取成功', $data);
    }
    /**
     * 查看
     */
    public function index()
    {
        $page = $this->request->post('page') ?? 1;
        if ($this->request->post('keyField')) {
            return $this->selectpage();
        }

        $childrenGroupIds = $this->childrenGroupIds;
        $groupName = AuthGroup::where('id', 'in', $childrenGroupIds)
            ->column('id,name');
        $authGroupList = AuthGroupAccess::where('group_id', 'in', $childrenGroupIds)
            ->field('uid,group_id')
            ->select();

        $adminGroupName = [];
        foreach ($authGroupList as $k => $v) {
            if (isset($groupName[$v['group_id']])) {
                $adminGroupName[$v['uid']][$v['group_id']] = $groupName[$v['group_id']];
            }
        }
        $groups = $this->auth->getGroups($this->auth->getAdminId());
        foreach ($groups as $m => $n) {
            $adminGroupName[$this->auth->id][$n['id']] = $n['name'];
        }

        $where = [];
        $step = 10;
        $start = ($page-1)*$step;
        $count = $this->model
            ->where(function ($query) use ($where) {
                $query->where($where);
            })
            ->where('id', 'in', $this->childrenAdminIds)
            ->count();

        $list = $this->model
            ->where(function ($query) use ($where) {
                $query->where($where);
            })
            ->where('id', 'in', $this->childrenAdminIds)
            ->field(['password', 'salt', 'token'], true)
            ->limit($start,$step)
            ->select();

        foreach ($list as $k => &$v) {
            $groups = isset($adminGroupName[$v['id']]) ? $adminGroupName[$v['id']] : [];
            $v['groups'] = implode(',', array_keys($groups));
            $v['groups_text'] = implode(',', array_values($groups));
        }
        unset($v);
        $result = array("total" => $count, "rows" => $list);

        $this->success('获取成功', $result);
    }

    /**
     * 添加
     */
    public function add()
    {
        $username = $this->request->post('username');
        $nickname = $this->request->post('nickname');
        $password = $this->request->post('password');
        $group = $this->request->post('group');
        $email = $this->request->post('email');
        $mobile = $this->request->post('mobile');

        $username ? $data['username'] = $username : $this->error(__('Username').'不能为空');
        $nickname ? $data['nickname'] = $nickname : $this->error(__('Nickname').'不能为空');
        $password ? $data['password'] = $password : $this->error(__('Password').'不能为空');
        $email ? $data['email'] = $email : '';
        $mobile ? $data['mobile'] = $mobile : '';
        if ($data){
            Db::startTrans();
            try {
                if (!Validate::is($password, '\S{6,30}')) {
                    exception(__("Please input correct password"));
                }
                $data['salt'] = Random::alnum();
                $data['password'] = $this->auth->getEncryptPassword($password, $data['salt']);
                $data['avatar'] = '/assets/img/avatar.png'; //设置新管理员默认头像。
                $result = $this->model->save($data);
                if ($result === false) {
                    exception($this->model->getError());
                }

                if ($group){
                    $group = explode(',', $group);
                }
                //过滤不允许的组别,避免越权
                $group = array_intersect($this->childrenGroupIds, $group);
                if (!$group) {
                    exception(__('The parent group exceeds permission limit'));
                }

                $dataset = [];
                foreach ($group as $value) {
                    $dataset[] = ['uid' => $this->model->id, 'group_id' => $value];
                }
                $AuthGroupAccess = new AuthGroupAccess();
                $AuthGroupAccess->saveAll($dataset);
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            $this->success('添加成功');
        }
        $this->error('添加失败');
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {

        $ids = $this->request->post('ids');
        $row = $this->model->get(['id' => $ids]);
        $username = $this->request->post('username');
        $nickname = $this->request->post('nickname');
        $password = $this->request->post('password') ?? '';
        $group = $this->request->post('group');
        $email = $this->request->post('email');
        $mobile = $this->request->post('mobile');

        $username ? $data['username'] = $username : $this->error(__('Username').'不能为空');
        $nickname ? $data['nickname'] = $nickname : $this->error(__('Nickname').'不能为空');
        $password ? $data['password'] = $password : '';
        $email ? $data['email'] = $email : '';
        $mobile ? $data['mobile'] = $mobile : '';
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if (!in_array($row->id, $this->childrenAdminIds)) {
            $this->error(__('You have no permission'));
        }

        if ($data){
            Db::startTrans();
            try {
                if ($password) {
                    if (!Validate::is($password, '\S{6,30}')) {
                        exception(__("Please input correct password"));
                    }
                    $data['salt'] = Random::alnum();
                    $data['password'] = $this->auth->getEncryptPassword($password, $data['salt']);
                } else {
                    unset($data['password'], $data['salt']);
                }
                //这里需要针对username和email做唯一验证
                $adminValidate = \think\Loader::validate('Admin','validate',false,'adminapi');
                $adminValidate->rule([
                    'username' => 'require|regex:\w{3,30}|unique:admin,username,' . $row->id,
                    'email'    => 'require|email|unique:admin,email,' . $row->id,
                    'mobile'   => 'regex:1[3-9]\d{9}|unique:admin,mobile,' . $row->id,
                    'password' => 'regex:\S{32}',
                ]);
                $result = $row->validate('Admin.edit')->save($data);
                if ($result === false) {
                    exception($this->model->getError());
                }

                if ($group){
                    $group = explode(',', $group);
                }
                //过滤不允许的组别,避免越权
                $group = array_intersect($this->childrenGroupIds, $group);
                if (!$group) {
                    exception(__('The parent group exceeds permission limit'));
                }

                $dataset = [];
                foreach ($group as $value) {
                    $dataset[] = ['uid' => $this->model->id, 'group_id' => $value];
                }
                $AuthGroupAccess = new AuthGroupAccess();
                $AuthGroupAccess->saveAll($dataset);
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            $this->success('添加成功');
        }
        $this->error('添加失败');
    }

    /**
     * 删除
     */
    public function del($ids = null)
    {
        $ids =  $this->request->post("ids");
        if ($ids) {
            $ids = array_intersect($this->childrenAdminIds, array_filter(explode(',', $ids)));
            // 避免越权删除管理员
            $childrenGroupIds = $this->childrenGroupIds;
            $adminList = $this->model->where('id', 'in', $ids)->where('id', 'in', function ($query) use ($childrenGroupIds) {
                $query->name('auth_group_access')->where('group_id', 'in', $childrenGroupIds)->field('uid');
            })->select();
            if ($adminList) {
                $deleteIds = [];
                foreach ($adminList as $k => $v) {
                    $deleteIds[] = $v->id;
                }
                $deleteIds = array_values(array_diff($deleteIds, [$this->auth->id]));
                if ($deleteIds) {
                    Db::startTrans();
                    try {
                        $this->model->destroy($deleteIds);
                        AuthGroupAccess::where('uid', 'in', $deleteIds)->delete();
                        Db::commit();
                    } catch (\Exception $e) {
                        Db::rollback();
                        $this->error($e->getMessage());
                    }
                    $this->success();
                }
                $this->error(__('No rows were deleted'));
            }
        }
        $this->error(__('You have no permission'));
    }

    /**
     * 批量更新
     * @internal
     */
    public function multi($ids = "")
    {
        // 管理员禁止批量操作
        $this->error();
    }

    /**
     * 下拉搜索
     */
    public function selectpage()
    {
        $this->dataLimit = 'auth';
        $this->dataLimitField = 'id';
        $data = parent::selectpage();
        $this->success('获取成功', $data);
    }
}
